package com.xinchuang.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinchuang.comment.R;
import com.xinchuang.common.Result;
import com.xinchuang.common.ResultUtil;
import com.xinchuang.entity.Permission;
import com.xinchuang.entity.Role;
import com.xinchuang.entity.RolePermission;
import com.xinchuang.entity.UserRole;
import com.xinchuang.mapper.PermissionMapper;
import com.xinchuang.mapper.RoleMapper;
import com.xinchuang.mapper.RolePermissionMapper;
import com.xinchuang.mapper.UserRoleMapper;
import com.xinchuang.service.RedisUseService;
import com.xinchuang.service.RoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class RoleServiceImpl implements RoleService {

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private final RoleMapper roleMapper;

    private final RolePermissionMapper rolePermissionMapper;

    private final PermissionMapper permissionMapper;

    private final RedisUseService redisUseService;

    private final UserRoleMapper userRoleMapper;

    @Override
    public String roleList() {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        List<Role> roleList = roleMapper.selectList(roleQueryWrapper);
        if (roleList.size() > 0) {
            return JSON.toJSONString(R.data(roleList));
        } else {
            return JSON.toJSONString(R.success("无数据"));
        }
    }

    @Override
    public String navList(JSONObject jsonObject) {
        //jsonobject解析获取类型
        String role = jsonObject.getString("role");
        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("role_id", role);
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(rolePermissionQueryWrapper);
        if (rolePermissions.size() > 0) {
            List<String> perIds = new ArrayList<>();
            for (RolePermission rolePermission : rolePermissions) {
                perIds.add(rolePermission.getPermissionId());
            }
            QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
            permissionQueryWrapper.in("id", perIds);
            List<Permission> permissions = permissionMapper.selectList(permissionQueryWrapper);
            JSONArray perArray = new JSONArray();
            for (Permission permission : permissions) {
                JSONObject permJson = new JSONObject();
                for (RolePermission rolePermission : rolePermissions) {
                    if (rolePermission.getPermissionId().equals(permission.getId())) {
                        permJson.put("accredit", rolePermission.getAccredit());
                        break;
                    }
                }
                permJson.put("id", permission.getId());
                permJson.put("subSysEName", permission.getPermission());
                permJson.put("subSysName", permission.getName());
                perArray.add(permJson);
            }
            return JSON.toJSONString(R.data(perArray));
        } else {
            return JSON.toJSONString(R.success("无数据"));
        }
    }

    @Override
    public Result roleAccredit(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取角色
        String role = jsonObject.getString("role");
        //jsonobject解析获取子系统标识
        String subSysName = jsonObject.getString("subSysName");
        //jsonobject解析获取授权
        String accredit = jsonObject.getString("accredit");

        String id = request.getHeader("Id");
        String userId = redisUseService.getUserId(id);
        UserRole userRole = userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
        if (ObjectUtil.isNull(userRole) || !"0".equals(userRole.getRoleId())) {
            return ResultUtil.error(500, "当前用户暂无权限修改");
        }

        if (!StringUtils.isNumeric(role)) {
            Role one = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRole, role));
            role = one.getId();
        }

        QueryWrapper<Permission> permissionQueryWrapper = new QueryWrapper<>();
        permissionQueryWrapper.eq("name", subSysName);
        Permission permission = permissionMapper.selectOne(permissionQueryWrapper);
        if (null != permission) {
            if (permission.getId().equals("4") && role.equals("0")) {
                return ResultUtil.error(500, "该权限不可被修改");
            }
            String permissionId = permission.getId();
            QueryWrapper<RolePermission> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("role_id", role);
            queryWrapper.eq("permission_id", permissionId);
            RolePermission rolePermissionExist = rolePermissionMapper.selectOne(queryWrapper);
            if (null != rolePermissionExist) {
                rolePermissionExist.setAccredit(accredit);
                rolePermissionMapper.update(rolePermissionExist, queryWrapper);
                return ResultUtil.success();
            }
        }
        return ResultUtil.error(500, "无数据");
    }

    @Override
    public Result accreditAll(JSONObject jsonObject, HttpServletRequest request) {
        //jsonobject解析获取授权所有
        String accreditAll = jsonObject.getString("accreditAll");
        //jsonobject解析获取类型
        String role = jsonObject.getString("role");

        String id = request.getHeader("Id");
        String userId = redisUseService.getUserId(id);
        UserRole userRole = userRoleMapper.selectOne(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId));
        if (ObjectUtil.isNull(userRole) || !"0".equals(userRole.getRoleId())) {
            return ResultUtil.error(500, "当前用户暂无权限修改");
        }

        if (!StringUtils.isNumeric(role)) {
            Role one = roleMapper.selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRole, role));
            role = one.getId();
        }

        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new LambdaQueryWrapper<RolePermission>()
                .eq(RolePermission::getRoleId, role));

        if (CollectionUtil.isNotEmpty(rolePermissions)) {
            for (RolePermission rolePermission : rolePermissions) {
                if (rolePermission.getRoleId().equals("0") && rolePermission.getPermissionId().equals("4")) {
                    rolePermission.setAccredit("true");
                } else {
                    rolePermission.setAccredit(accreditAll);
                }
                rolePermissionMapper.updateAccredit(rolePermission);
            }
            return ResultUtil.success();
        }
        return ResultUtil.error(500 ,"无数据");
    }

}
